package cn.jl.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

/**
 * @author LongJunLin
 * @version 创建时间：2021年1月15日 下午3:32:55
 * @Description 类描述
 */

@Slf4j
public class TestLock {

	private Lock testLock = new ReentrantLock();

	private int i = 0;

	// 用来测试“线程”调用该方法时是否可中断
//	private void test1() {
//		while (true) {
//			testLock.lock();
//			try {
//				log.info("进入方法1");
//			} finally {
//				log.info("释放");
//				testLock.unlock();
//				log.info(Thread.currentThread().isInterrupted() + "");
//			}
//		}
//	}
	private void test1() {
		while (true) {
			try {
				testLock.lockInterruptibly();
			} catch (InterruptedException e) {
				log.info("进入这里方法");
//				e.printStackTrace();
			}
			try {
				log.info("进入方法1");
			} finally {
				log.info("释放");
				testLock.unlock();
				log.info(Thread.currentThread().isInterrupted() + "");
			}
		}
	}

	// 用来造成死锁，配合测试
	private void test2() {
		log.info("进入死锁方法");
		testLock.lock(); // 故意不释放
		log.info("方法2拿到锁");
	}

	public static void main(String[] args) {
		TestLock test = new TestLock();

		Runnable r1 = () -> {
			test.test1();
		};
		Runnable r2 = () -> {
			test.test2();
		};
		Thread t1 = new Thread(r1, "test1");
		Thread t2 = new Thread(r2, "test2");

		t1.start();
		t2.start();
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("准备调用t1的中断");
		t1.interrupt();
	}

}
